package com.wisenet.wx.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.wisenet.common.Const;
import com.wisenet.common.WxConst;
import com.wisenet.entity.ImageTextInfo;
import com.wisenet.entity.ImageTextMore;
import com.wisenet.entity.MessageInfo;
import com.wisenet.pojo.respmsgpojo.Article;
import com.wisenet.pojo.respmsgpojo.Music;
import com.wisenet.pojo.respmsgpojo.MusicMessage;
import com.wisenet.pojo.respmsgpojo.NewsMessage;

/**
 * 图文消息管理类
 * @author fzh
 *
 */
public class MessageManager {
	public static Logger logger = Logger.getLogger(MessageManager.class);
	
	/**
	 * 获取图文信息
	 * @param requestMap
	 * @param imageTextInfo
	 * @param imagetextMoreList
	 * @return
	 * @throws Exception
	 */
	public static String getImageTextInfo(Map<String, String> requestMap, ImageTextInfo imageTextInfo, List<ImageTextMore> imagetextMoreList)throws Exception{
		String picUrl = imageTextInfo.getImageUrl();
		String clickUrl = Const.MAIN_CLICK_URL + imageTextInfo.getImageTextNo();
		
		List<Article> articleList = new ArrayList<Article>();
		Article article = new Article();
		article.setPicUrl(picUrl);
		article.setUrl(clickUrl);
		article.setTitle(imageTextInfo.getTitle());
		article.setDescription(imageTextInfo.getDigest());
	
		if (StringUtils.isNotEmpty(imageTextInfo.getClickOutUrl())) {
			article.setUrl(imageTextInfo.getClickOutUrl() + "?openid=" + requestMap.get(WxConst.FROM_USER_NAME)); //如果外链不为空则为外链
		}
		articleList.add(article);
		
		// 判断是否多图文
		if (Const.MESSAGE_TYPE_IMAGE.equals(imageTextInfo.getImageTextType())) {
			for (ImageTextMore textMore : imagetextMoreList) {
				article = new Article();
				// 图文消息标题 
				article.setTitle(textMore.getTitle());
				 
				picUrl = textMore.getImageUrl();
				clickUrl = Const.MORE_CLICK_URL + textMore.getMoreImageTextNo();
				// 点击图文消息跳转链接
				article.setUrl(clickUrl);
				article.setPicUrl(picUrl);
				article.setDescription(textMore.getDigest());
				if (StringUtils.isNotEmpty(textMore.getClickOutUrl())) {
					// 如果外链不为空则为外链
					article.setUrl(textMore.getClickOutUrl() + "?openid=" + requestMap.get(WxConst.FROM_USER_NAME));
				}
				articleList.add(article);
			}
		}
		return getNewsMessage(requestMap, articleList);
	}
	
	/**
	 * 回复关键字电影图文
	 * @param requestMap
	 * @param imageTextInfo
	 * @param movieNames
	 * @return
	 */
	public static String getMovieNewsMessage(Map<String, String> requestMap, ImageTextInfo imageTextInfo, String movieNames) {
		List<Article> articleList = new ArrayList<Article>();
		//电影图文
		Article article = new Article();
		article.setPicUrl(imageTextInfo.getImageUrl());
		article.setUrl(imageTextInfo.getClickOutUrl());
		article.setTitle(imageTextInfo.getTitle());
		article.setDescription(imageTextInfo.getDigest());
		articleList.add(article);
		//1元打赏
		article = new Article();
		article.setUrl("http://mp.weixin.qq.com/s?__biz=MzAxODk3MDA0Mw==&mid=100000003&idx=3&sn=43286afe089abc833214da0800d020ea#rd");
		article.setTitle(StringUtil.getTitle());
		article.setPicUrl("http://mmbiz.qpic.cn/mmbiz/FAahqknuAWlen3HL6SS6J7D79gPN42aiaAFkicwcvqyicnicPLwrcZpAGUgMe9w6tZg8lVGpsV6zAIbY9t1MB8cVwg/0?wx_fmt=jpeg");
		article.setDescription("阿伯影院 微信号：abyy008 （观看电影请回复电影名，如：人妻）");
		articleList.add(article);
		//公号互推
		article = new Article();
		article.setUrl("http://mp.weixin.qq.com/s?__biz=MzAxODk3MDA0Mw==&mid=100000003&idx=3&sn=43286afe089abc833214da0800d020ea#rd");
		article.setTitle("关注更多公众号，长期免费观看更多好电影！");
		article.setPicUrl("http://mmbiz.qpic.cn/mmbiz/FAahqknuAWlen3HL6SS6J7D79gPN42aiaAFkicwcvqyicnicPLwrcZpAGUgMe9w6tZg8lVGpsV6zAIbY9t1MB8cVwg/0?wx_fmt=jpeg");
		article.setDescription("阿伯影院 微信号：abyy008 （观看电影请回复电影名，如：人妻）");
		articleList.add(article);
		//电影名字
		article = new Article();
		if("gh_0fa2eb502321".equals(requestMap.get(WxConst.TO_USER_NAME))) {
			article.setTitle("10部随机电影名单：\n" + movieNames + "\n\n观看电影请回复：电影+名字");
		} else {
			article.setTitle("10部随机电影名单：\n" + movieNames + "\n\n观看电影请回复电影名");
		}
		article.setDescription("阿伯影院 微信号：abyy008 （观看电影请回复电影名，如：人妻）");
		articleList.add(article);
		return getNewsMessage(requestMap, articleList);
	}
	
	public static String getTextMessage(Map<String, String> requestMap, ImageTextInfo imageTextInfo, String movieNames) {
		String content = "%s\n%s\n（如无法播放，请复制链接在手机浏览器打开！）\n%s\n\n10部随机电影（回复名字观看）：\n%s";
		content = String.format(content, 
						imageTextInfo.getTitle(),
						imageTextInfo.getClickOutUrl(),
						"<a href=\"https://mmbiz.qpic.cn/mmbiz_jpg/FrKmF09vc5AN5ekqDibNd3ENM0KjhIgWam6Px8Pfzv3gzLGMicleTagSu2CX3E5ib6MopqAhHCxRfVicJY32jSa5Dw/0?wx_fmt=jpeg\">支持阿伯</a>",
						movieNames + "\n\n请点击电影链接进入网页搜索！");
		return MessageUtil.replyTextMessage(requestMap.get(WxConst.FROM_USER_NAME), requestMap.get(WxConst.TO_USER_NAME), content);
	}
	
	/**
	 * 消息记录
	 * @param requestMap
	 * @param imageTextNo
	 * @param remsgType
	 * @param url
	 * @param keyword
	 * @return
	 */
	public static MessageInfo createMessageInfo(Map<String, String> requestMap, Long imageTextNo,
			String remsgType, String url, String keyword) {
		String msgType = requestMap.get(MessageUtil.MESSAGE_TYPE);
		String menuKey = requestMap.get(MessageUtil.EVENT_KEY);
		
		MessageInfo messageInfo = new MessageInfo();
		messageInfo.setUrl(menuKey);
		messageInfo.setMsgType(msgType);
		messageInfo.setKeyword(keyword);
		messageInfo.setImageNo(imageTextNo);
		messageInfo.setRemsgType(remsgType);
		messageInfo.setMsgSendTime(new Date());
		messageInfo.setMsgContent(requestMap.get(WxConst.CONTENT));
		messageInfo.setOpenId(requestMap.get(WxConst.FROM_USER_NAME));
		messageInfo.setPublicNo(requestMap.get(WxConst.TO_USER_NAME));
		
		// url保存对应的menuKey
		messageInfo.setMenuKey(url != null ? url : menuKey);
		if (MessageUtil.REQ_MESSAGE_TYPE_LOCATION.equals(msgType)) {
			messageInfo.setLocation(requestMap.get("Location_X") + "," + requestMap.get("Location_Y"));
		}
		return messageInfo;
	}
	
	/**
	 * 疯狂猜图 图文消息
	 * @param requestMap
	 * @param ids
	 * @return
	 */
	public static String getGuessImageMessage(Map<String, String> requestMap, String ids) {
		String title = null, picUrl = null, descrition = null;
		String type = requestMap.get(MessageUtil.EVENT_KEY).trim();
		if (Const.MENU_TYPE_GUESS_IMAGE.equals(type)) {
			title = "疯狂猜图，第" + ids + "关";
			descrition = "查看答案：请回复 猜图+关数，如：猜图1";
			picUrl = String.format(Const.GUESS_IMG_URL, "ques" + ids);
		} else if (Const.MENU_TYPE_GUESS_IDIOM.equals(type)) {
			title = "疯狂成语，第" + ids + "关";
			descrition = "查看答案：请回复 成语+关数，如：成语1";
			picUrl = String.format(Const.GUESS_IMG_URL, "question" + ids);
		}
		String detailUrl = String.format(Const.GUESS_IMG_DETAIL_URL, type, requestMap.get(WxConst.FROM_USER_NAME));
	
		Article article = new Article();
		article.setTitle(title);
		article.setPicUrl(picUrl);
		article.setUrl(detailUrl);
		article.setDescription(descrition);
		List<Article> articles = new ArrayList<Article>();
		articles.add(article);
		return getNewsMessage(requestMap, articles);
	}
	
	/**
	 * 音乐消息
	 * @param requestMap
	 * @return
	 */
	public static String getMusicMsg(Map<String, String> requestMap) {
		 String title = requestMap.get("title");
		 String author = requestMap.get("author");
		 
		 Music music = new Music();
		 music.setMusicUrl(requestMap.get("musicUrl"));
		 music.setHQMusicUrl(requestMap.get("musicUrl"));
		 music.setDescription("喜欢就转发给朋友听吧，按住转发！");
		
		 MusicMessage musicMessage = new MusicMessage();
		 musicMessage.setMusic(music);
		 musicMessage.setCreateTime(new Date().getTime());
		 musicMessage.setFromUserName(requestMap.get(WxConst.TO_USER_NAME));
		 musicMessage.setToUserName(requestMap.get(WxConst.FROM_USER_NAME));
		 musicMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_MUSIC);
		 music.setTitle(author.length() > 1 ? (title + "-" + author) : title);
		 return MessageUtil.musicMessageToXml(musicMessage);
	}
	
	/**
	 * 组装图文消息
	 * @param requestMap
	 * @param articles
	 * @return
	 */
	public static String getNewsMessage(Map<String, String> requestMap, List<Article> articles) {
		NewsMessage newsMessage = new NewsMessage();
		newsMessage.setArticles(articles);
		newsMessage.setArticleCount(articles.size());
		newsMessage.setToUserName(requestMap.get("FromUserName"));
		newsMessage.setFromUserName(requestMap.get("ToUserName"));
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		newsMessage.setCreateTime(Long.parseLong(requestMap.get("CreateTime")));
		return MessageUtil.newsMessageToXml(newsMessage);
	}
	
	/**
	 * 回复单图文消息
	 * @param requestMap
	 * @param article
	 * @return
	 */
	public static String getSingleNews(Map<String, String> requestMap, Article article) {
		List<Article> articleList = new ArrayList<Article>();
		articleList.add(article);
		NewsMessage newsMessage = new NewsMessage();
		newsMessage.setArticles(articleList);
		newsMessage.setArticleCount(articleList.size());
		newsMessage.setToUserName(requestMap.get(WxConst.FROM_USER_NAME));
		newsMessage.setFromUserName(requestMap.get(WxConst.TO_USER_NAME));
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		newsMessage.setCreateTime(Long.parseLong(requestMap.get("CreateTime")));
		return MessageUtil.newsMessageToXml(newsMessage);
	}
	
}
